const { ethers } = require("hardhat");
const hre = require("hardhat");

async function main() {
    // 创建合约工厂
    let fundMeFactory = await ethers.getContractFactory("FundMe");
    console.log("Deploying FundMe contract...");
    let fundMe = await fundMeFactory.deploy(100);
    await fundMe.waitForDeployment();
    console.log("FundMe contract deployed to:", fundMe.target);
    console.log("Deploying FundMe contract...done");

    // 部署合约并等待合约同步到 Etherscan
    if (hre.network.config.chainId === 11155111 && process.env.ETHER_SCAN_API_KEY9999999999999999) {
        console.log("Waiting for Etherscan to verify the contract...");
        // 验证合约
        await fundMe.deploymentTransaction().wait(5);
        await hre.run("verify:verify", {
            address: fundMe.target,
            constructorArguments: [100],
        });
    } else {
        console.log("verify skipped");
    }

    const [firstAccount, secondAccount] = await ethers.getSigners();
    console.log("firstAccount address:", firstAccount.address);

    // 使用第一个账户支付
    let fundTx = await fundMe.fund({ value: ethers.parseEther("0.001") });
    await fundTx.wait();
    console.log("fundTx hash:", fundTx.hash);

    // 查看 fundMe 的余额
    let balanceOneStep = await ethers.provider.getBalance(fundMe.target);
    console.log("fundMe balance:", balanceOneStep);

    // 使用第二个账户支付
    const fundTxWithSecondAccount = await fundMe.connect(secondAccount).fund({ value: ethers.parseEther("0.003") });
    await fundTxWithSecondAccount.wait();
    console.log("fundTx hash:", fundTxWithSecondAccount.hash);

    // 查看 fundMe 的余额
    let balancetowStep = await ethers.provider.getBalance(fundMe.target);
    console.log("fundMe balance:", balancetowStep);

    // 获取账户的贡献金额
    const firstAccountAmount = await fundMe.fundersToAmount(firstAccount.address);
    const secondAccountAmount = await fundMe.fundersToAmount(secondAccount.address);

    console.log("firstAccount.address:", firstAccount.address, "         firstAccountAmount:", firstAccountAmount.toString());
    console.log("secondAccount.address:", secondAccount.address, "         secondAccountAmount:", secondAccountAmount.toString());
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error);
        process.exit(1);
    });